/*
 * This file is part of the Sx Framework Library.
 * 
 * Copyright (C) 2013 University of Colorado Denver
 * <min.choi@ucdenver.edu>
 * <shane.transue@ucdenver.edu>
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy 
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 * copies of the Software, and to permit persons to whom the Software is 
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in 
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 * DEALINGS IN THE SOFTWARE.
 */
#include <sxQConsole.h>
#include <sxQDebugStream.h>
#include <fstream>

const static char* DEFAULT_FONT = "Courier New";

Sx::QtInterface::System::QConsole::QConsole(QWidget* parent, std::ostream* stream, const String& logFilename) : QPlainTextEdit(parent) {
	this->setAcceptDrops(false);
	this->setContextMenuPolicy(Qt::NoContextMenu);
	this->setUndoRedoEnabled(false);
	this->setReadOnly(true);
	this->setFont(QFont(DEFAULT_FONT));

	this->debugStream = new QDebugStream(stream, this, logFilename);
}

Sx::QtInterface::System::QConsole::~QConsole() {
	delete this->debugStream;
}

void Sx::QtInterface::System::QConsole::setConsoleCursorToEnd() {
	QTextCursor cursor(this->textCursor());
	cursor.movePosition(QTextCursor::End);
	this->setTextCursor(cursor);
}

void Sx::QtInterface::System::QConsole::setLogFilename(const String& filename) {
	if ( this->debugStream == nullptr ) return;
	this->debugStream->setLogFilename(filename);
}

bool Sx::QtInterface::System::QConsole::setStream(std::ostream* stream) {
	if ( this->debugStream == nullptr ) return false;
	this->debugStream->setStream(stream);
	return true;
}

void Sx::QtInterface::System::QConsole::onAppend(const QString& text) {
	this->appendPlainText(text);
}

void Sx::QtInterface::System::QConsole::onLogAppend(const QString& text) {
	std::ofstream log;
	log.open(this->debugStream->getLogFilename().toAscii().constData(), std::ios_base::app);
	log << text.toAscii().constData() << std::endl;
	log.close();
}
